package com.luyu.rabbitmqdemo.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author luYu
 */
@Configuration(proxyBeanMethods = true)
public class RabbitConfig {
    @Bean
    public Queue ConfirmQueue(){
        return  new Queue("fanout.queue1");
    }
    @Bean
    public FanoutExchange ConfirmExchange(){
        return new FanoutExchange("amq.fanout");
    }
    @Bean
    public Binding ConfirmBinding(Queue ConfirmQueue,FanoutExchange  ConfirmExchange){
        return BindingBuilder.bind(ConfirmQueue).to(ConfirmExchange);
    }
    @Bean
    public DirectExchange errorMessageExchange(){
        return new DirectExchange("error.direct");
    }
    @Bean
    public Queue errorQueue(){
        return new Queue("error.queue", true);
    }
    @Bean
    public Binding errorBinding(Queue errorQueue, DirectExchange errorMessageExchange){
        return BindingBuilder.bind(errorQueue).to(errorMessageExchange).with("error");
    }
    @Bean
    public RepublishMessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate,"err.direct","error");
    }


    @Bean
    public Queue ttlQueue(){
        return QueueBuilder.durable("ttl.queue")
                .ttl(10000)//设置队列的超时时间，10秒
                .deadLetterExchange("dl.ttl.direct")  // 指定死信交换机
                .build();
    }
    @Bean
    public DirectExchange ttlExchange(){
        return new DirectExchange("ttl.dir");
    }
    @Bean
    public Binding ttlBinding(){
        return BindingBuilder.bind(ttlQueue()).to(ttlExchange()).with("ttl");
    }


    @Bean
    public DirectExchange lazyExchange(){
        return new DirectExchange("lazy.dir");
    }
    @Bean
    public Queue lazyQueue(){
        return QueueBuilder.durable("lazy.beanQueue")
                .withArgument("key","beanQueue")
                .lazy()
                .build();
    }
    @Bean
    public RabbitTemplate luyuRabbitmqTemplate(ConnectionFactory connectionFactory, RabbitTemplate.ReturnsCallback r, RabbitTemplate.ConfirmCallback c){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setReturnsCallback(r);
        rabbitTemplate.setConfirmCallback(c);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        return  rabbitTemplate;
    }
}
